<?php
/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file license.txt or that can be found at 
 * http://code.google.com/p/billboardce/wiki/License.
 *
 * @package    Sign_IndexController
 * @category   Controller
 * @license    http://code.google.com/p/billboardce/wiki/License New BSD License
 * @version    SVN: $Id: $
 */

/**
 * Main controller for the slide interface to the application
 *
 * @package    Sign_IndexController
 * @category   Controller
 */
class Sign_IndexController extends Zend_Controller_Action 
{   
          
    /**
     * The main sign interface
     *
     */
    public function indexAction()
    {
        $ip = $_SERVER['REMOTE_ADDR'];
                
        $device = new Device();
        $slidestreamDevice = new Slidestream_Device();
        
        $where = $device->getAdapter()->quoteInto('ip = ?', $ip)
               . ' AND '
               . $device->getAdapter()->quoteInto('enabled = ?', 1);
               
        $thisDevice = $device->fetchAll($where);
        
        $isRegistered = true;
        
        if ($thisDevice->count() == 0) {
            $isRegistered = false;
        }
        
        $slidestreamId = $slidestreamDevice->getSlidestreamForDevice($thisDevice->current()->deviceId);
        
        if (is_null($slidestreamId)) {
            $isRegistered = false;
        }

        $this->view->manualView = false;
        $this->view->isRegistered = $isRegistered;
        $this->view->slidestreamId = $slidestreamId;
        $this->_helper->viewRenderer->setNeverRender();
        $this->_helper->layout()->setLayoutPath(APPLICATION_PATH . '/layouts/');
        $this->_helper->layout()->setLayout('sign');
    }
    
    public function viewAction()
    {
        $get = Zend_Registry::get('getFilter');

        if (!isset($get->slidestreamId) || empty($get->slidestreamId)) {
            throw new Ot_Exception_Input('No slidestream ID provided');
        }
        
        $this->view->manualView = true;
        $this->view->slidestreamId = $get->slidestreamId;
        $this->_helper->viewRenderer->setNeverRender();
        $this->_helper->layout()->setLayoutPath(APPLICATION_PATH . '/layouts/');
        $this->_helper->layout()->setLayout('sign');
    }
    
    /**
     * The page to display an image slide
     */
    public function slideAction()
    {
        $this->_helper->layout->disableLayout();
        
        $get = Zend_Registry::get('getFilter');
        
        $slide = new Slide();
        
        $thisSlide = $slide->find($get->slideId);
        
        $this->view->screenHeight = $get->bbceScreenHeight;
        $this->view->screenWidth  = $get->bbceScreenWidth;
        
        if (!is_null($thisSlide)) {
            try {
                $module = Slidetype::factory($thisSlide->slideType);
    
                $this->view->setScriptPath(Slidetype::getSlidetypePath($thisSlide->slideType));
                $this->_helper->viewRenderer->setViewScriptPathSpec(':action.:suffix');
                
                $vars = $module->buildSlide($thisSlide->slideId);
                
                foreach ($vars as $key => $value) {
                    $this->view->{$key} = $value;
                }
                
            } catch (Exception $e) {
                $this->view->error = $e->getMessage();
            }
        }
    }
    
    public function getLastUpdateTimestampAction() {

        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNeverRender();
        
        $get = Zend_Registry::get('getFilter');
        
        $checkRegistration = false;
        
        if (!isset($get->slidestreamId) || empty($get->slidestreamId)) {
            $checkRegistration = true;
        }
        
        // it's only a manual view if the sign was pointed to a specific slidestream
        $manualView = false;
        
        if (isset($get->manual) || empty($get->manual)) {
            $manualView = ($get->manual == 'true') ? true : false;
        }
        
        $slidestreamId = $get->slidestreamId;
        
        $slidestream = new Slidestream();
        
        $thisSlidestream = $slidestream->find($slidestreamId);
        
        if (is_null($thisSlidestream)) {
            $checkRegistration = true;
        }
        
        $ip = $_SERVER['REMOTE_ADDR'];
        
        $device = new Device();
        $slidestreamDevice = new Slidestream_Device();
        
        $where = $device->getAdapter()->quoteInto('ip = ?', $ip)
                   . ' AND '
                   . $device->getAdapter()->quoteInto('enabled = ?', 1);

        $thisDevice = $device->fetchRow($where);
        
        if (!is_null($thisDevice)) {
            $thisDevice = $thisDevice->toArray();
        }

        // if the device doesn't exist, but it's a manually set slidestream,
        // then we don't need to check the registration
        if (is_null($thisDevice) && $manualView == true) {
            $checkRegistration = false;
        }
        
        // no slidestreamID was passed or it wasn't found and the device was found
        if ($checkRegistration && !is_null($thisDevice)) {
            
            $isRegistered = true;
            
            $slidestreamId = null;
            
            if (is_null($thisDevice)) {
                $isRegistered = false;
            } else {
                $slidestreamId = $slidestreamDevice->getSlidestreamForDevice($thisDevice['deviceId']);
            }
            
            if (is_null($slidestreamId)) {
                $isRegistered = false;
            }
            
            if ($isRegistered) {
                // device wasn't registered to anything or was registered to a 
                // slidestream that didn't exist, but it is now, so refresh.
                $ret = array('updateTimestamp' => time(), 'msg' => 'Device not registered or was registered to a slidestream that did not exist, but it is now, so refresh');
            } else {
                // isn't registered, don't refresh
                $ret = array('updateTimestamp' => 0, 'msg' => 'Device not registered, do not refresh');
            }
            
        } else {           

            // if the device isn't found and it wasn't a manually set slidestream, we need to refresh
            if (is_null($thisDevice) && $manualView == false) {
                
                $ret = array('updateTimestamp' => time(), 'msg' => 'Device not found, not manually set slidestream');
                
            } else {
            
                // make sure the device is actually assigned to the slidestream ID that is passed
                $slidestreamId = $slidestreamDevice->getSlidestreamForDevice($thisDevice['deviceId']);
                
                if (is_null($slidestreamId) && $manualView == false) {
                    // device exists but isn't registered to this slidestream any more. refresh sign.
                    $ret = array('updateTimestamp' => time(), 'msg' => 'Device exists, but is not registered anymore, refresh');
                    
                } else {
                    // this is the slidestream that the sign is registered to, so just send the
                    // slidestream's update time so it'll refresh if and when it needs to.
                    $ret = array('updateTimestamp' => $thisSlidestream->updateTimestamp, 'msg' => 'Device is registered and all good');
                }
            }
        }
        
        // the message is really just for informational purposes, so we can just remove it
        unset($ret['msg']);
        
        echo Zend_Json::encode($ret);
    }
    
    
    /**
     * Looks up the data for the given slidestream ID and echoes it as JSON
     * 
     */
    public function getDataAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNeverRender();
        
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->slidestreamId) || empty($get->slidestreamId)) {
            
            $entities = array('slides' => array());
            
        } else {
        
            $slidestreamId = $get->slidestreamId;
            
            $slidestreamMap = new Slidestream_Slide();
            
            $entities = $slidestreamMap->getEntitiesForSlideStream($slidestreamId);
        }
        
        echo Zend_Json::encode($entities);
    }
}